from django.db import models
from django.contrib.admin.models import User
import datetime
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.core.mail import EmailMultiAlternatives

MOMENT = 120    # duration in seconds within which the time difference 
                # will be rendered as 'a moment ago'

def naturalTimeDifference(value):
    """
    Finds the difference between the datetime value given and now()
    and returns appropriate humanize form
    """
    delta = datetime.datetime.utcnow() - value

    if delta.days > 6:
        return value.strftime("%b %d")                    # May 15
    if delta.days > 1:
        return value.strftime("%A")                       # Wednesday
    elif delta.days == 1:
        return 'yesterday'                                # yesterday
    elif delta.seconds > 3600:
        return str(delta.seconds / 3600 ) + ' hours ago'  # 3 hours ago
    elif delta.seconds >  MOMENT:
        return str(delta.seconds/60) + ' minutes ago'     # 29 minutes ago
    else:
        return 'a moment ago'
    
class Message(models.Model):
    
    user_lookup = models.CharField(max_length=500,null=True,verbose_name='To User') #An AJAX lookup field
    
    from_user = models.ForeignKey(User,null=True,related_name='from_messages')
    to_user = models.ForeignKey(User,null=True,related_name='to_messages')
    subject = models.CharField(max_length=500,null=True)
    message = models.TextField(null=True,blank=True)
    
    when_created = models.DateTimeField(null=True,blank=True)
    
    in_response_to = models.ForeignKey('self',null=True,blank=True, related_name='child')
    
    @property
    def time_since(self):
        return naturalTimeDifference(self.when_created)
        
    
    def save(self,*args,**kwargs):
        
        if not self.id:
            self.when_created = datetime.datetime.utcnow()
        super(Message,self).save(*args,**kwargs)
        
        #Send the user an email
        the_email = None
        try:
            if self.to_user.email:
                the_email = self.to_user.email
            elif self.to_user.get_profile().email:
                the_email = self.to_user.get_profile().email
        except:
            pass
            
        if the_email:
            to = [self.to_user.email]
            from_email = 'no-reply@lawyertolawyerny.com'
            
            html_content = render_to_string('email_templates/new_message_alert.html', {'message':self})
            text_content = strip_tags(html_content)
            msg = EmailMultiAlternatives('New message on L2L.com from %s!' % self.from_user, text_content, from_email, to)
            msg.attach_alternative(html_content, "text/html")
            msg.send(fail_silently=False)
        
    class Meta:
        ordering = ('-when_created',)
